package com.xfpp.javaDemo.factory.spring;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ClassPathXmlApplicationContext implements BeanFactory{
	private Map<String,Object> map = new HashMap<String,Object>();
	
	@SuppressWarnings("rawtypes")
	public ClassPathXmlApplicationContext(String fileName) {
//		File inputXml = new File(fileName);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(fileName));
            Element users = document.getRootElement();
            /*List<Element> list = users.elements();
            for(int i=0, length = list.size(); i<length; i++){
            	System.out.println(list.get(i).attributeValue("id"));
            }*/
            System.out.println(users.getNamespaceURI());
            for (Iterator i = users.elementIterator(); i.hasNext();) {
                Element user = (Element) i.next();
                map.put(user.attributeValue("id"), user.attributeValue("class"));
                System.out.println(user.attributeValue("id") + ":" + user.attributeValue("class"));
                for (Iterator j = user.elementIterator(); j.hasNext();) {
                    Element node = (Element) j.next();
                    System.out.println(node.getName() + ":" + node.getText());
                }
            }
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
        }
	}

	@Override
	public Object getBean(String name) {
		return map.get(name);
	}
	
	public static void main(String[] args) {
		new ClassPathXmlApplicationContext("com/xfpp/javaDemo/factory/spring/applicationContext.xml");
	}
}
